<template>
  <div class="env-variable-box">
    <Row v-for="environment in env" :key="environment.id" class="environment-row">
      <Col span="9">
        <Input v-model.trim="environment.name" placeholder="key(由英文字母，数字，_组成)" @on-blur="validateKey" @on-focus="addEnvironment(environment)"></Input>
      </Col>
      <Col span="9">
        <Input v-model.trim="environment.value" placeholder="value" @on-blur="$limitLen"></Input>
      </Col>
      <Col span="4">
        <Icon type="ios-add-circle-outline" class="add-icon" @click="addEnvironment()" />
        <Icon type="ios-remove-circle-outline" class="remove-icon" v-if="env.length > 1" @click="minusEnvironment(environment)" />
      </Col>
    </Row>
  </div>
</template>
<script type="text/javascript">
import uuid from 'uuid/v4'

export default {
  name: 'EnvironmentVariable',
  data() {
    return {
    }
  },
  props: {
    env: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  methods: {
    // 键校验
    validateKey(event) {
      if (event.currentTarget.value) {
        if (!/^[A-Za-z0-9]+[A-Za-z0-9_]*$/.test(event.currentTarget.value)) {
          event.currentTarget.value = ''
        }
        if (event.currentTarget.value.length > 128) {
          event.currentTarget.value = event.currentTarget.value.substring(0, 127)
        }
      }
    },
    // 减少环境变量
    minusEnvironment(environment) {
      this.$emit('update:env', this.env.filter((env) => {
        return env.id !== environment.id
      }))
    },
    // 添加环境变量
    addEnvironment(environment) {
      // 用于限制无限制添加
      if (this.env.length > 20) {
        this.$Message.info({
          content: '环境变量不能超过20个',
          duration: this.DURATION
        })
        return
      }
      // environment存在， 且是最后一个key并且key为空时，则通过key键新增
      if ((environment && this.env.length > 0 &&
        environment.id === this.env[this.env.length - 1].id && !environment.name) ||
        !environment) {
        let temp = this.env
        temp.push({
          id: uuid(),
          name: '',
          value: ''
        })
        this.$emit('update:env', temp)
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.env-variable-box {
  .icon-jian {
    font-size: 20px;
    color: #e45049;
    cursor: pointer;
    &:hover {
      color: #e45049;
    }
  }
}
.env-variable-box /deep/ {
  .ivu-col {
    margin-right: 10px;
  }
}
.environment-row {
  margin-bottom: 10px;
  .remove-icon {
    margin-top: 4px;
  }
  .add-icon {
    display: inline-block;
    margin-right: 10px;
    font-size: 20px;
    color: #3ea9f5;
    cursor: pointer;
    margin-top: 4px;
  }
}
</style>
